﻿namespace Atomic.Plugins.Users.Controllers
{
    using System;
    using System.Web;
    using System.Web.Mvc;

    using Atomic.Images;
    using Atomic.Modules.Security;

    using Atomic.Mvc.Filters;
    using Atomic.Mvc.Settings;

    using Atomic.Core.Security;

    using Atomic.Plugins.Users.Application;
    using Atomic.Plugins.Users.Domain;

    /// <summary>
    /// 用户控制器。
    /// </summary>
    [Layout]
    public class UserController : Controller
    {
        /// <summary>
        /// 站点信息。
        /// </summary>
        private readonly ISite _site = null;

        /// <summary>
        /// 会员服务。
        /// </summary>
        private readonly IMembershipService _membershipService = null;

        /// <summary>
        /// 认证服务。
        /// </summary>
        private readonly IAuthenticationService _authenticationService = null;

        /// <summary>
        /// 用户应用服务。
        /// </summary>
        private readonly IUserAppService _userAppService = null;

        /// <summary>
        /// 初始化账户控制器。
        /// </summary>
        /// <param name="membershipService">会员服务。</param>
        /// <param name="authenticationService">认证服务。</param>
        /// <param name="accountAppService">用户应用服务。</param>
        public UserController(IMembershipService membershipService, IAuthenticationService authenticationService, IUserAppService userAppService)
        {
            this._membershipService = membershipService;
            this._authenticationService = authenticationService;
            this._userAppService = userAppService;

            this._site = SiteFactory.Current;
        }

        /// <summary>
        /// 显示用户信息。
        /// </summary>
        /// <param name="accountNumber"></param>
        /// <returns></returns>
        [Layout(Messages.USER_ADMIN_LAYOUT)]
        public ActionResult Index(string accountNumber)
        {
            UserDescriptor user = this._userAppService.GetUser(accountNumber);

            if (user != null)
            {
                return View(user);
            }

            ViewData["Message"] = "找不到该用户。";

            return this.View("Error");
        }

        #region 用户注册

        /// <summary>
        /// 用户注册。
        /// </summary>
        /// <returns></returns>
        [AtomicAuthorize(Permissions.User_Register)]
        public ActionResult Register()
        {
            if (this.Request.IsAuthenticated)
            {
                return this.Redirect(this._site.HomePage);
            }

            return View();
        }

        /// <summary>
        /// 用户注册。
        /// </summary>
        /// <param name="registerNewUserModel">用户注册信息。</param>
        /// <returns></returns>
        [AtomicAuthorize(Permissions.User_Register)]
        [HttpPost]
        public ActionResult Register(RegisterNewUserModel registerNewUserModel)
        {
            if (this.ModelState.IsValid)
            {
                var result = this._userAppService.RegisterNewUser(registerNewUserModel);

                if (result)
                {
                    //注册成功后进行自动登录。
                    var user = this._membershipService.GetUserByAccountNumber(registerNewUserModel.AccountNumber);

                    this._authenticationService.SignIn(user, false);

                    ViewData["Message"] = "注册成功";

                    return this.View("Success");
                }
            }

            return View(registerNewUserModel);
        }

        #endregion

        #region 修改密码

        /// <summary>
        /// 修改密码。
        /// </summary>
        /// <returns></returns>
        [Login]
        [Layout(Messages.USER_ADMIN_LAYOUT)]
        public ActionResult ChangePassword()
        {
            return View();
        }

        /// <summary>
        /// 修改密码。
        /// </summary>
        /// <param name="changePasswordModel">修改密码信息。</param>
        /// <returns></returns>
        [Login]
        [Layout(Messages.USER_ADMIN_LAYOUT)]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel changePasswordModel)
        {
            if (this.ModelState.IsValid)
            {
                changePasswordModel.AccountNumber = this.User.GetCurrentAccountNumber();

                var result = this._userAppService.ChangePassword(changePasswordModel);

                if (ChangePasswordStatus.Success == result)
                {
                    ViewData["Message"] = "修改密码成功";

                    return this.View("Success");
                }
                else
                {
                    switch (result)
                    {
                        case ChangePasswordStatus.OldPasswordError:
                            this.ModelState.AddModelError("OldPassword", "您输入的旧密码错误。");
                            break;
                        case ChangePasswordStatus.ConfirmPasswordError:
                            this.ModelState.AddModelError("ConfirmPasswordError", "您输入的新密码与确认密码不一致");
                            break;
                    }
                }
            }

            return View(changePasswordModel);
        }

        #endregion

        #region 修改头像

        /// <summary>
        /// 修改头像。
        /// </summary>
        /// <returns></returns>
        [Login]
        [Layout(Messages.USER_ADMIN_LAYOUT)]
        [AtomicAuthorize(Permissions.User_Settings)]
        public ActionResult Icon()
        {
            return this.View();
        }

        /// <summary>
        /// 修改并裁剪头像。
        /// </summary>
        /// <param name="cutImage"></param>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        [Login]
        [Layout(Messages.USER_ADMIN_LAYOUT)]
        [AtomicAuthorize(Permissions.User_Settings)]
        [HttpPost]
        public ActionResult Icon(CutImageModel cutImage)
        {
            cutImage.AreaWidth = this._site.IconAreaWidth;
            cutImage.AreaHeight = this._site.IconAreaHeight;

            var result = this._userAppService.ChangeIcon(this.User.GetCurrentAccountNumber(), cutImage);

            return Json((int)result);
        }

        /// <summary>
        /// 原始头像上传。
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [Login]
        [Layout(Messages.USER_ADMIN_LAYOUT)]
        [AtomicAuthorize(Permissions.User_Settings)]
        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase fileData)
        {
            var user = this._authenticationService.GetAuthenticatedUser();

            if (fileData != null)
            {
                UploadImage uploadImage = new UploadImage
                {
                    Stream = fileData.InputStream,
                    FileName = fileData.FileName,
                    SavePath = this._site.SaveIconPath,
                    Width = this._site.IconAreaWidth,
                    Height = this._site.IconAreaHeight
                };

                var view = this._userAppService.UploadIcon(user.Id, uploadImage);

                return Json(view);
            }

            return Content("0");
        }

        #endregion
    }
}